package antspool

import (
	"sync"

	"github.com/mars/pkg/loggers"
	"github.com/mars/pkg/randid"
	"github.com/panjf2000/ants/v2"
)

var (
	poolNameCache map[string]*ants.Pool
	uuid          = randid.NewSecureRandom(8)
	_mu           sync.RWMutex
)

func NewNameAntPool(name string, poolSize int) (pool *ants.Pool, err error) {
	if pool, err = ants.NewPool(poolSize, ants.WithPreAlloc(true), ants.WithLogger(loggers.Instance()),
		ants.WithPanicHandler(func(err interface{}) {
			loggers.Errorf("ants pool panic: %v", err)
		})); err != nil {
		return nil, err
	}

	_mu.Lock()
	defer _mu.Unlock()
	if poolNameCache == nil {
		poolNameCache = make(map[string]*ants.Pool)
	}
	poolNameCache[name] = pool
	return pool, nil
}

func PoolFree(name string) int {
	_mu.RLock()
	defer _mu.RUnlock()
	pool := poolNameCache[name]
	return pool.Free()
}

func Release() {
	_mu.RLock()
	defer _mu.RUnlock()
	for _, pool := range poolNameCache {
		pool.Release()
	}
}
